package com.sz.admin.system.controller;

import com.sz.core.common.entity.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件监控测试控制器
 * 用于测试文件监控功能，创建测试文件等
 *
 * @author sz-admin
 * @since 2025-01-13
 */
@Tag(name = "文件监控测试")
@RestController
@RequestMapping("/system/fileMonitorTest")
@RequiredArgsConstructor
@Slf4j
public class FileMonitorTestController {

    @Operation(summary = "创建测试目录")
    @PostMapping("/createTestDir")
    public ApiResult<String> createTestDirectory(@RequestParam(defaultValue = "D:\\file\\img") String path) {
        try {
            Path dirPath = Paths.get(path);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
                log.info("创建测试目录成功: {}", path);
                return ApiResult.success("测试目录创建成功: " + path);
            } else {
                return ApiResult.success("测试目录已存在: " + path);
            }
        } catch (IOException e) {
            log.error("创建测试目录失败: {}", e.getMessage(), e);
            return new ApiResult<>("-1", "创建测试目录失败: " + e.getMessage());
        }
    }

    @Operation(summary = "创建测试图片文件")
    @PostMapping("/createTestFile")
    public ApiResult<String> createTestFile(@RequestParam(defaultValue = "D:\\file\\img") String dirPath,
                                           @RequestParam(defaultValue = "test_image.jpg") String filename) {
        try {
            Path dir = Paths.get(dirPath);
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            }

            File testFile = new File(dir.toFile(), filename);
            
            // 创建一个简单的测试文件（模拟图片文件）
            try (FileWriter writer = new FileWriter(testFile)) {
                writer.write("This is a test image file created at: " + System.currentTimeMillis());
                writer.write("\nFilename: " + filename);
                writer.write("\nCreated for testing file monitoring system.");
            }

            log.info("创建测试文件成功: {}", testFile.getAbsolutePath());
            return ApiResult.success("测试文件创建成功: " + testFile.getAbsolutePath());
            
        } catch (IOException e) {
            log.error("创建测试文件失败: {}", e.getMessage(), e);
            return new ApiResult<>("-1", "创建测试文件失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量创建测试文件")
    @PostMapping("/createBatchTestFiles")
    public ApiResult<String> createBatchTestFiles(@RequestParam(defaultValue = "D:\\file\\img") String dirPath,
                                                  @RequestParam(defaultValue = "5") int count) {
        try {
            Path dir = Paths.get(dirPath);
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            }

            String[] extensions = {"jpg", "png", "gif", "bmp", "webp"};
            int created = 0;

            for (int i = 1; i <= count; i++) {
                String extension = extensions[i % extensions.length];
                String filename = "test_image_" + System.currentTimeMillis() + "_" + i + "." + extension;
                File testFile = new File(dir.toFile(), filename);

                try (FileWriter writer = new FileWriter(testFile)) {
                    writer.write("Test image file #" + i);
                    writer.write("\nCreated at: " + System.currentTimeMillis());
                    writer.write("\nFile type: " + extension);
                    writer.write("\nThis is a test file for monitoring system validation.");
                }

                created++;
                log.info("创建测试文件: {}", testFile.getAbsolutePath());
                
                // 间隔创建，避免太快
                Thread.sleep(1000);
            }

            return ApiResult.success("成功创建 " + created + " 个测试文件");
            
        } catch (Exception e) {
            log.error("批量创建测试文件失败: {}", e.getMessage(), e);
            return new ApiResult<>("-1", "批量创建测试文件失败: " + e.getMessage());
        }
    }

    @Operation(summary = "检查目录状态")
    @GetMapping("/checkDirectory")
    public ApiResult<String> checkDirectory(@RequestParam(defaultValue = "D:\\file\\img") String path) {
        try {
            Path dirPath = Paths.get(path);
            if (!Files.exists(dirPath)) {
                return ApiResult.success("目录不存在: " + path);
            }

            if (!Files.isDirectory(dirPath)) {
                return ApiResult.success("路径存在但不是目录: " + path);
            }

            File dir = dirPath.toFile();
            File[] files = dir.listFiles();
            int fileCount = files != null ? files.length : 0;

            StringBuilder info = new StringBuilder();
            info.append("目录存在: ").append(path).append("\n");
            info.append("文件数量: ").append(fileCount).append("\n");
            
            if (files != null && fileCount > 0) {
                info.append("文件列表:\n");
                for (File file : files) {
                    if (file.isFile()) {
                        info.append("- ").append(file.getName())
                            .append(" (").append(file.length()).append(" bytes)\n");
                    }
                }
            }

            return ApiResult.success(info.toString());
            
        } catch (Exception e) {
            log.error("检查目录状态失败: {}", e.getMessage(), e);
            return new ApiResult<>("-1", "检查目录状态失败: " + e.getMessage());
        }
    }

    @Operation(summary = "手动测试文件监控")
    @PostMapping("/testMonitoring")
    public ApiResult<String> testFileMonitoring(@RequestParam(defaultValue = "D:\\file\\img") String dirPath) {
        try {
            Path dir = Paths.get(dirPath);
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
                log.info("创建测试目录: {}", dirPath);
            }

            // 创建一个带时间戳的测试图片文件
            String timestamp = String.valueOf(System.currentTimeMillis());
            String filename = "monitor_test_" + timestamp + ".jpg";
            File testFile = new File(dir.toFile(), filename);
            
            // 写入一些测试内容
            try (FileWriter writer = new FileWriter(testFile)) {
                writer.write("Test image file for monitoring system");
                writer.write("\nCreated at: " + new java.util.Date());
                writer.write("\nTimestamp: " + timestamp);
                writer.write("\nThis file should be detected by the monitoring system.");
            }

            log.info("创建监控测试文件: {}", testFile.getAbsolutePath());
            return ApiResult.success("测试文件已创建: " + testFile.getAbsolutePath() + "\n请检查日志以确认文件是否被监控系统检测到。");
            
        } catch (Exception e) {
            log.error("测试文件监控失败", e);
            return new ApiResult<>("-1", "测试失败: " + e.getMessage());
        }
    }

    @Operation(summary = "创建子目录和测试文件")
    @PostMapping("/createSubdirTest")
    public ApiResult<String> createSubdirectoryTest(@RequestParam(defaultValue = "D:\\file\\img") String basePath) {
        try {
            Path baseDir = Paths.get(basePath);
            if (!Files.exists(baseDir)) {
                Files.createDirectories(baseDir);
                log.info("创建基础目录: {}", basePath);
            }

            // 创建多个子目录
            String[] subdirs = {"subfolder1", "subfolder2", "camera01"};
            StringBuilder result = new StringBuilder();
            result.append("创建子目录和测试文件:\n");
            
            for (String subdir : subdirs) {
                Path subdirPath = baseDir.resolve(subdir);
                Files.createDirectories(subdirPath);
                result.append("创建目录: ").append(subdirPath).append("\n");
                
                // 在每个子目录中创建2个测试文件
                for (int i = 1; i <= 2; i++) {
                    String timestamp = String.valueOf(System.currentTimeMillis());
                    String filename = subdir + "_test_" + i + "_" + timestamp + ".jpg";
                    File testFile = new File(subdirPath.toFile(), filename);
                    
                    try (FileWriter writer = new FileWriter(testFile)) {
                        writer.write("Test image file for subdirectory monitoring\n");
                        writer.write("Subdirectory: " + subdir + "\n");
                        writer.write("File number: " + i + "\n");
                        writer.write("Created at: " + new java.util.Date() + "\n");
                        writer.write("Timestamp: " + timestamp + "\n");
                        writer.write("This file should be detected by the monitoring system.\n");
                    }
                    
                    result.append("创建文件: ").append(testFile.getAbsolutePath()).append("\n");
                    log.info("在子目录中创建测试文件: {}", testFile.getAbsolutePath());
                    
                    // 间隔创建，避免太快
                    Thread.sleep(500);
                }
            }

            return ApiResult.success(result.toString());
            
        } catch (Exception e) {
            log.error("创建子目录测试失败", e);
            return new ApiResult<>("-1", "创建子目录测试失败: " + e.getMessage());
        }
    }

}